package com.mjf.jst.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mjf.jst.config.JSTConfig;
import com.mjf.jst.enums.JSTApiEnum;
import com.mjf.jst.util.RequestUtil;
import com.mjf.jst.util.SignUtil;
import com.mjf.jst.vo.BcCjstSkuVO;
import com.mjf.jst.vo.JstSalesOutVO;
import com.mjf.jst.vo.ShopInfoVO;
import com.mjf.jst.vo.WMSInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/7/7 23:10
 */
@Slf4j
@Service
public class JSTAsyncService {

    @Autowired
    private JSTConfig jstConfig;
    @Autowired
    private RequestUtil requestUtil;
    /**
     * 同步店铺
     */
    public List<ShopInfoVO.ShopInfoDataList> pullShopsList() {

        long timestamp = System.currentTimeMillis() / 1000;
        Map<String, Object> paramMap = new HashMap<>();
        Integer page_index = 1;
        Integer page_size = 100;
        paramMap.put("page_index", page_index);
        paramMap.put("page_size", page_size);
        List<ShopInfoVO.ShopInfoDataList> shopInfoDataLists = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        Boolean next = true;
        try {
            while (next) {
                next = false;
                paramMap.put("page_index", page_index);
                String biz = JSON.toJSONString(paramMap);
                String signature = getSignature(jstConfig.getAppKey(), jstConfig.getAppSecret(), jstConfig.getAccessToken(), biz, timestamp);
                MultiValueMap<String, String> paramss = buildParams(jstConfig.getAppKey(), jstConfig.getAccessToken(), timestamp, biz, signature);
                String repsp = requestUtil.reqForRespByUrlencoded(jstConfig.getUrl() + JSTApiEnum.SHOP_QUERY.getUrl(), paramss,
                    JSTApiEnum.SHOP_QUERY.getName());
                // 转实体
                ShopInfoVO shopInfoVO = objectMapper.readValue(repsp, ShopInfoVO.class);
                if (ObjectUtil.isNotNull(shopInfoVO.getData())
                    && CollectionUtil.isNotEmpty(shopInfoVO.getData().getDatas())) {
                    shopInfoDataLists.addAll(shopInfoVO.getData().getDatas());
                }
                if (ObjectUtil.isNotNull(shopInfoVO.getData()) && ObjectUtil.isNotNull(shopInfoVO.getData().getHas_next())) {
                    next = shopInfoVO.getData().getHas_next();
                }
                page_index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("聚水潭拉取店铺 失败 ", e);
        }
        return shopInfoDataLists;
    }

    /**
     * 同步仓库
     */
    public List<WMSInfoVO.WMSInfoDataList> pullWmsList() {

        long timestamp = System.currentTimeMillis() / 1000;
        Map<String, Object> paramMap = new HashMap<>();
        Integer page_index = 1;
        Integer page_size = 100;
        paramMap.put("page_index", page_index);
        paramMap.put("page_size", page_size);
        List<WMSInfoVO.WMSInfoDataList> wmsInfoDataLists = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        Boolean next = true;
        try {
            while (next) {
                next = false;
                paramMap.put("page_index", page_index);
                String biz = JSON.toJSONString(paramMap);
                String signature = getSignature(jstConfig.getAppKey(), jstConfig.getAppSecret(), jstConfig.getAccessToken(), biz, timestamp);
                MultiValueMap<String, String> paramss = buildParams(jstConfig.getAppKey(), jstConfig.getAccessToken(), timestamp, biz, signature);
                String repsp = requestUtil.reqForRespByUrlencoded(jstConfig.getUrl() + JSTApiEnum.SHOP_QUERY.getUrl(), paramss,
                    JSTApiEnum.SHOP_QUERY.getName());
                // 转实体
                WMSInfoVO wmsInfoVO = objectMapper.readValue(repsp, WMSInfoVO.class);
                if (ObjectUtil.isNotNull(wmsInfoVO.getData())
                    && CollectionUtil.isNotEmpty(wmsInfoVO.getData().getDatas())) {
                    wmsInfoDataLists.addAll(wmsInfoVO.getData().getDatas());
                }
                if (ObjectUtil.isNotNull(wmsInfoVO.getData()) && ObjectUtil.isNotNull(wmsInfoVO.getData().getHas_next())) {
                    next = wmsInfoVO.getData().getHas_next();
                }
                page_index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("聚水潭拉取仓库 失败 ", e);
        }
        return wmsInfoDataLists;
    }


    /**
     * 同步销售出库单
     * @param start
     * @param end
     * @return
     */
    public List<JstSalesOutVO.OutInfoDataList> asyncSalesout(String start, String end) {
        long timestamp = System.currentTimeMillis() / 1000;
        Map<String, Object> paramMap = new HashMap<>();
        Integer page_index = 1;
        Integer page_size = 100;
        paramMap.put("page_index", page_index);
        paramMap.put("page_size", page_size);
        paramMap.put("modified_begin", start);
        paramMap.put("modified_end", end);
        paramMap.put("date_type", 2); // 时间类型 2-出库时间
        List<JstSalesOutVO.OutInfoDataList> vos = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        Boolean next = true;
        try {
            while (next) {
                next = false;
                paramMap.put("page_index", page_index);
                String biz = JSON.toJSONString(paramMap);
                String signature = getSignature(jstConfig.getAppKey(), jstConfig.getAppSecret(), jstConfig.getAccessToken(), biz, timestamp);
                MultiValueMap<String, String> paramss = buildParams(jstConfig.getAppKey(), jstConfig.getAccessToken(), timestamp, biz, signature);
                String repsp = requestUtil.reqForRespByUrlencoded(jstConfig.getUrl() + JSTApiEnum.SALESOUT_QUERY.getUrl(), paramss,
                    JSTApiEnum.SALESOUT_QUERY.getName());
                // 转实体
                JstSalesOutVO outVO = objectMapper.readValue(repsp, JstSalesOutVO.class);
                if (ObjectUtil.isNotNull(outVO.getData())
                    && CollectionUtil.isNotEmpty(outVO.getData().getDatas())) {
                    vos.addAll(outVO.getData().getDatas());
                } else {
                    log.info("聚水潭销售出库单无更多数据");
                    log.info(repsp);
                }
                if (ObjectUtil.isNotNull(outVO.getData()) && ObjectUtil.isNotNull(outVO.getData().getHas_next())) {
                    next = outVO.getData().getHas_next();
                }
                page_index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("聚水潭销售出库单失败 ", e);
        }
        return vos;
    }

    /**
     * 同步商品
     * @return
     */
    public List<BcCjstSkuVO.SkuDataList> asyncProduct(String start, String end) {
        long timestamp = System.currentTimeMillis() / 1000;
        List<BcCjstSkuVO.SkuDataList> vos = new ArrayList<>();
        Map<String, Object> paramMap = new HashMap<>();
        Integer page_index = 1;
        Integer page_size = 100;
        paramMap.put("page_index", page_index);
        paramMap.put("page_size", page_size);
        paramMap.put("modified_begin", start);
        paramMap.put("modified_end", end);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        Boolean next = true;
        try {
            while (next) {
                next = false;
                paramMap.put("page_index", page_index);
                String biz = JSON.toJSONString(paramMap);
                String signature = getSignature(jstConfig.getAppKey(), jstConfig.getAppSecret(), jstConfig.getAccessToken(), biz, timestamp);
                MultiValueMap<String, String> paramss = buildParams(jstConfig.getAppKey(), jstConfig.getAccessToken(), timestamp, biz, signature);
                String repsp = requestUtil.reqForRespByUrlencoded(jstConfig.getUrl() + JSTApiEnum.PRODUCT_QUERY.getUrl(), paramss,
                    JSTApiEnum.PRODUCT_QUERY.getName());
                // 转实体
                BcCjstSkuVO skuVO = objectMapper.readValue(repsp, BcCjstSkuVO.class);
                if (ObjectUtil.isNotNull(skuVO.getData())
                    && CollectionUtil.isNotEmpty(skuVO.getData().getDatas())) {
                    vos.addAll(skuVO.getData().getDatas());
                } else {
                    log.info(JSTApiEnum.PRODUCT_QUERY.getName() + "无更多数据");
                    log.info(repsp);
                }
                if (ObjectUtil.isNotNull(skuVO.getData()) && ObjectUtil.isNotNull(skuVO.getData().getHas_next())) {
                    next = skuVO.getData().getHas_next();
                }
                page_index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JSTApiEnum.PRODUCT_QUERY.getName() + "失败 ", e);
        }
        return vos;

    }

    /**
     * 获取签名
     *
     * @param app_key      app_key
     * @param app_secret   app_secret
     * @param access_token access_token
     * @param biz          access_token
     * @param timestamp    timestamp
     * @return String
     */
    private String getSignature(String app_key, String app_secret, String access_token, String biz, long timestamp) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", app_key);
        params.put("access_token", access_token);
        params.put("timestamp", Long.toString(timestamp));
        params.put("version", "2");
        params.put("charset", "utf-8");
        params.put("biz", biz);
        return SignUtil.getSign(app_secret, params);
    }
    /**
     * buildParams
     *
     * @param app_key      app_key
     * @param access_token app_key
     * @param timestamp    timestamp
     * @param biz          biz
     * @param signature    signature
     * @return MultiValueMap
     */
    private MultiValueMap<String, String> buildParams(String app_key, String access_token, long timestamp, String biz,
                                                      String signature) {
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("app_key", app_key);
        paramMap.add("access_token", access_token);
        paramMap.add("timestamp", Long.toString(timestamp));
        paramMap.add("version", "2");
        paramMap.add("charset", "utf-8");
        paramMap.add("biz", biz);
        paramMap.add("sign", signature);
        return paramMap;
    }


}
